<template>
    <div>
        <van-nav-bar left-arrow>
            <template #title>
                <van-search v-model="keyword" placeholder="请输入搜索关键词" />
            </template>
            <template #right>
                <!-- <van-icon name="search" size="18" /> -->
                <span @click="searchFn">搜索</span>
            </template>
        </van-nav-bar>
        <div class="box">
            <h1>历史记录</h1>
            <ul>
                <li v-for="(val,index) in history" 
                :key="index" @click="searchHistory(val)">{{ val }}</li>
            </ul>
        </div>
        <div class="box">
            <h1>搜索结果</h1>
            <ul class="result-box">
                <li v-for="item in list" 
                :key="item.id"
                v-html="item.title.replace(keyword, `<span style='color: red'>${keyword}</span>` )"
                @click="$router.push({path: '/articleDetail',query:{id: item.id}})">
                <!-- {{item.title}} -->
                </li>
            </ul>
        </div>
    </div>
</template>

<script>
import { post_search } from "@/api/news.js"
export default {
    data(){
        return {
            keyword: "",
            list: [],
            history: JSON.parse(localStorage.getItem("history"))||[]
        }
    },
    methods: {
        searchHistory(val){
            this.keyword = val;
            this.searchFn()
        },
        searchFn(){
            if(!this.keyword){return this.$toast.fail("搜索关键词不能为空！")}
            // 判断数组中是否存在关键词，如果没有加入数组中
            if(this.history.indexOf(this.keyword) === -1){
                this.history.push(this.keyword)
                localStorage.setItem("history", JSON.stringify(this.history))
            }

            post_search({
                keyword: this.keyword
            }).then(res=>{
                // console.log(44,res)
                this.list = res.data.data
            })
        }
    }
}
</script>

<style lang="less" scoped>
/deep/.van-nav-bar{
    border: 1px solid #ddd;
    .van-search{
        padding: 6px 12px;
    }
    .van-search__content{
        border-radius: 20px;
    }
    .van-icon-arrow-left,
    .van-icon-search{
        color: #000;
    }
}
.box{
    padding: 20px 10px;
    h1{
        font-size: 20px;
        font-weight: bold;
    }
    ul{
        margin-top: 10px;
        li{
            margin: 5px;
        }
    }
    .result-box{
        li{
            text-decoration: underline;
            color: #666;
        }
    }
}
</style>